import { onBeforeUnmount, ref, shallowRef } from 'vue';
import * as Cesium from 'cesium';
import { getDef, update3dTilesMatrix } from './utils';

interface useCesiumParams {
  onClickCb: (e: any) => void;
}
const useCesium = (params: useCesiumParams) => {
  const target = ref<HTMLElement | null>(null);
  const viewer = shallowRef<Cesium.Viewer>({} as Cesium.Viewer);
  const tileset = shallowRef<Cesium.Cesium3DTileset>({} as Cesium.Cesium3DTileset);

  /**
   *  初始化viewer
   * @returns
   */
  const initViewer = () => {
    if (!target.value) return;
    viewer.value = new Cesium.Viewer('cesiumContainer', {
      timeline: false,
      animation: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      baseLayerPicker: false,
      navigationHelpButton: false,
      fullscreenButton: false
      // terrainProvider: new Cesium.CesiumTerrainProvider({
      //   url: 'http://data.marsgis.cn/terrain'
      // })
    });
    // 显示帧率
    viewer.value.scene.debugShowFramesPerSecond = true;
    viewer.value.scene.globe.depthTestAgainstTerrain = true;

    const handler = new Cesium.ScreenSpaceEventHandler(viewer.value.scene.canvas);
    handler.setInputAction(movement => {
      // const clickPosition = viewer.value!.scene.camera.pickEllipsoid(e.position);
      const getCartesianCoordinate = pos => {
        //获取点击位置的经纬度
        console.log('pos: ', pos);
        const cartesianCoordinate = viewer.value.scene.pickPosition(pos);
        if (!cartesianCoordinate) {
          return null;
        }
        const cartographic = Cesium.Cartographic.fromCartesian(cartesianCoordinate); //将笛卡尔坐标转换为地理坐标
        const longitude = Cesium.Math.toDegrees(cartographic.longitude);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude);
        const height = cartographic.height;
        const position = {
          longitude: Number(longitude.toFixed(6)),
          latitude: Number(latitude.toFixed(6)),
          altitude: Number(height.toFixed(2))
        };
        console.log('坐标: ', position);
        return position;
      };
      // console.log('clickPosition: ', clickPosition);
      //经纬度-高度转换笛卡尔坐标
      // const Cartesian3 = Cesium.Cartesian3.fromDegrees(110, 10, 30);
      // console.log('Cartesian3:经纬度-高度转换笛卡尔坐标 ', Cartesian3);
      //笛卡尔坐标转弧度
      // Cesium.BillboardGraphics;
      // const Cartographic = Cesium.Cartographic.fromCartesian(Cartesian3);
      // console.log('Cartographic:笛卡尔坐标 -转为弧度 ', Cartographic);
      //弧度转经纬度
      // const lon = Cesium.Math.toDegrees(Cartographic.longitude);
      // const lat = Cesium.Math.toDegrees(Cartographic.latitude);
      // const height = Cartographic.height;
      // console.log('经度：' + lon + ', 纬度：' + lat + ', 高度：' + height);
      // const getCartesianCoordinate = (pos) => {
      //   //获取点击位置的经纬度
      //   console.log('pos: ', pos)
      //   let cartesianCoordinate = viewer.scene.pickPosition(pos)
      //   if (!cartesianCoordinate) {
      //     return null
      //   }
      //   let cartographic = //将笛卡尔坐标转换为地理坐标
      //     Cesium.Cartographic.fromCartesian(cartesianCoordinate)
      //   let longitude = Cesium.Math.toDegrees(cartographic.longitude)
      //   let latitude = Cesium.Math.toDegrees(cartographic.latitude)
      //   let height = cartographic.height
      //   let position = {
      //     longitude: Number(longitude.toFixed(6)),
      //     latitude: Number(latitude.toFixed(6)),
      //     altitude: Number(height.toFixed(2)),
      //   }
      //   console.log('坐标: ', position)
      //   return position
      // }

      //笛卡尔坐标转弧度
      // const pos = Cesium.Cartographic.fromCartesian(clickPosition as any);
      // console.log('pos: ', pos.height);
      // //弧度转经纬度
      // console.log(
      //   '经度：' +
      //     Cesium.Math.toDegrees(pos.longitude) +
      //     ', 纬度：' +
      //     Cesium.Math.toDegrees(pos.latitude)
      // );
      const location = getCartesianCoordinate(movement.position);
      // console.log('location: ', location);
      // 在这里被调用的onClickCb
      const buildData = params.onClickCb(location);
      console.log(buildData);
      //buildData - 就是 ，是传下去的
      // 这里就是buildData
      addColorBox(buildData);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  };

  /**
   * 加载3Dtiles
   */
  const load = async () => {
    const url1 = `${location.origin}/cesium/maanqiepian/tileset.json`;

    console.log('url1: ', url1);
    tileset.value = await Cesium.Cesium3DTileset.fromUrl(url1, { ...getDef() });
    viewer.value.scene.primitives.add(tileset.value);
    viewer.value.zoomTo(tileset.value);
    viewer.value.flyTo(tileset.value, {
      duration: 3,
      offset: {
        heading: Cesium.Math.toRadians(45), //方向
        pitch: Cesium.Math.toRadians(-35), //倾斜角度
        range: 600
      }
    });
    // 设置场景时间
    viewer.value.clock.currentTime = Cesium.JulianDate.fromDate(new Date(`2025/9/12 12:00:00`));
    tileset.value.root.transform = update3dTilesMatrix({
      tileSet: tileset.value,
      lng: 120.62581, //Number(transform.lng),经度
      lat: 30.161275, // Number(transform.lat),纬度
      alt: 5.27, //Number(transform.alt),高度
      x: 0, //Number(transform.x),绕X轴旋转
      y: 0, //Number(transform.y),绕Y轴旋转
      z: 0, // Number(transform.z),绕Z轴旋转
      scale: 1 //Number(transform.scale),模型比例
    });
  };

  onBeforeUnmount(() => {
    viewer.value?.destroy?.();
  });

  const _box = shallowRef<Cesium.ClassificationPrimitive | null>(null);
  const addColorBox = buildInfo => {
    //buildInfo 是函数的入参 ， 是行参，只是一个名称，代称，具体是什么内容，由调用者决定
    _box.value && viewer.value.scene.primitives.remove(_box.value);

    const cartesian3 = Cesium.Cartesian3.fromDegrees(
      buildInfo.lng,
      buildInfo.lat,
      buildInfo.heigh + 6
    );

    const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(cartesian3);
    const mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(buildInfo.mz));
    Cesium.Matrix4.multiplyByMatrix3(modelMatrix, mz, modelMatrix);
    const instance = new Cesium.GeometryInstance({
      geometry: Cesium.BoxGeometry.fromDimensions({
        vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
        dimensions: new Cesium.Cartesian3(buildInfo.length, buildInfo.width, buildInfo.height)
        // dimensions: new Cesium.Cartesian3(buildInfo.width, 20, 2.8)
      }),
      modelMatrix,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          new Cesium.Color(1.0, 0.0, 0.0, 0.5)
        ),
        show: new Cesium.ShowGeometryInstanceAttribute(true) //设置初始化后是否显示
      }
      //   id: item.buildNum + '-' + `${i + 1}`
    });
    _box.value = new Cesium.ClassificationPrimitive({
      geometryInstances: instance,
      classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
    });
    viewer.value.scene.primitives.add(_box.value);
  };
  return {
    target,
    viewer,
    tileset,
    initViewer,
    load
  };
};

export { useCesium };
